# coding: utf-8
import io
import os

import web
from PIL import Image

from libs import utils
from libs.utils import db, show_error, render, set_self_user, show_success


class user:
    @set_self_user
    def GET(self, username):
        try:
            user = db.select('user', where={'username': username})[0]
        except Exception as e:
            return show_error(f'用户 {username} 不存在')
        else:
            return render('user/user', action=self, user=user)


class profile:
    @set_self_user
    def GET(self):
        return render('user/profile', action=self)

    def POST(self):
        post = web.input(face={})
        old_password = post.old_password
        password = post.password
        password_confirm = post.password_confirm
        face = post.face

        _user = utils.get_current_user()

        if old_password or password or password_confirm:
            result_dict = self.__change_password(_user, old_password, password, password_confirm)
            if not result_dict['success']:
                return show_error(result_dict['message'])

        if face.filename:
            result_dict = self.__upload_face(_user, face)
            if not result_dict['success']:
                return show_error(result_dict['message'])

        return show_success('资料修改成功', '')

    def __change_password(self, _user, old_password, password, password_confirm):
        password_db = _user.password
        salt = _user.salt
        create_time = utils.format_time1(_user.create_time)

        if password_db != utils.sha1(old_password + salt + create_time):
            return {'success': 0, 'message': '原密码错误'}
        elif password != password_confirm:
            return {'success': 0, 'message': '两次输入密码不一致'}
        else:
            password_db = utils.sha1(password + salt + create_time)
            db.update('user', password=password_db, where={'id': _user.id})

            return {'success': 1, 'message': ''}

    def __upload_face(self, _user, face):
        file_name = face.filename
        img_bytes = face.file.read()
        ext = os.path.splitext(file_name)[1]

        new_file_name = f'sitedata/faces/{_user.id}_{utils.generate_random_str(10)}{ext}'
        real_file_path = utils.real_path(new_file_name)

        with Image.open(io.BytesIO(img_bytes)) as im:

            # todo 截取正方形

            im.thumbnail((200, 200))
            im.save(real_file_path)

        old_face = _user.face
        db.update('user', face=new_file_name, where={'id': _user.id})

        old_face_real_path = utils.real_path(old_face)
        if os.path.isfile(old_face_real_path):
            os.remove(old_face_real_path)

        return {'success': 1, 'message': ''}


class show_face:
    def GET(self, user_id):
        _user = utils.get_user(user_id)
        user_face_path = utils.real_path(_user.face)

        with open(user_face_path, 'rb') as file:
            img_bytes = file.read()

        return img_bytes
